// 游戏常量
const BOARD_WIDTH = 7;
const BOARD_HEIGHT = 7;
const PIECE_TYPES = {
    PAWN: { name: '卒', value: 10, type: 'PAWN' },
    ADVISOR: { name: '士', value: 10, type: 'ADVISOR' },
    KNIGHT: { name: '马', value: 15, type: 'KNIGHT' },
    ELEPHANT: { name: '象', value: 15, type: 'ELEPHANT' },
    ROOK: { name: '车', value: 30, type: 'ROOK' },
    CANNON: { name: '炮', value: 30, type: 'CANNON' },
    GENERAL: { name: '将', value: 100, type: 'GENERAL' }
};

// 游戏状态
let gameBoard = [];
let playerPiece = null;
let enemyPieces = [];
let score = 0;
let totalScore = parseInt(localStorage.getItem('chessTotalScore')) || 0;
let highScore = localStorage.getItem('chessGameHighScore') || 0;
let round = 1;
let gameOver = false;
let combo = 0;

// 辅助模式
let assistMode = false;

// 棋子升级 - 存储在localStorage中
let pieceUpgrades = JSON.parse(localStorage.getItem('chessUpgrades')) || {
    PAWN: 0,
    ADVISOR: 0,
    KNIGHT: 0,
    ELEPHANT: 0,
    ROOK: 0,
    CANNON: 0,
    GENERAL: 0
};

// 跟踪上一步移动用于高亮显示
let lastMoveFrom = null;
let lastMoveTo = null;

// DOM元素
const gameBoardElement = document.getElementById('game-board');
const scoreElement = document.getElementById('score');
const totalScoreElement = document.getElementById('total-score');
const highScoreElement = document.getElementById('high-score');
const roundElement = document.getElementById('round');
const startButton = document.getElementById('start-button');
const shopButton = document.getElementById('shop-button');
const assistButton = document.getElementById('assist-button');
const shopElement = document.getElementById('shop');
const gameOverElement = document.getElementById('game-over');
const finalScoreElement = document.getElementById('final-score');
const messageElement = document.getElementById('message');
const restartButton = document.getElementById('restart-button');
const killAudio = document.getElementById("kill-audio");
const soundToggle = document.getElementById("sound-toggle");

// 获取升级后的棋子分值
function getUpgradedValue(pieceType) {
    const baseValue = PIECE_TYPES[pieceType].value;
    const upgradeLevel = pieceUpgrades[pieceType];
    return Math.floor(baseValue + (baseValue * 0.5 * upgradeLevel));
}

// 获取升级费用
function getUpgradeCost(pieceType) {
    const currentValue = getUpgradedValue(pieceType);
    return currentValue * 10;
}

// 用新的升级分值更新棋盘上现有的棋子
function updateExistingPieces(pieceType) {
    const newValue = getUpgradedValue(pieceType);

    // 更新棋盘上的敌方棋子
    enemyPieces.forEach(piece => {
        if (piece.type.type === pieceType) {
            piece.type.value = newValue;
        }
    });

    // 更新gameBoard数组中的棋子
    for (let y = 0; y < BOARD_HEIGHT; y++) {
        for (let x = 0; x < BOARD_WIDTH; x++) {
            const piece = gameBoard[y][x];
            if (piece && !piece.isPlayer && piece.type.type === pieceType) {
                piece.type.value = newValue;
            }
        }
    }

    console.log(`已将所有${pieceType}棋子更新为分值${newValue}`);
}

// 切换辅助模式
function toggleAssistMode() {
    assistMode = !assistMode;
    assistButton.textContent = assistMode ? '辅助: 开' : '辅助: 关';
    assistButton.classList.toggle('active', assistMode);
    renderBoard();
}

// 获取敌方攻击区域（对于炮来说与移动不同）
function getEnemyAttackZones(piece) {
    const attackZones = [];

    switch (piece.type.type) {
        case 'CANNON':
            // 炮只能通过跳过一个棋子来攻击
            let jumpedHorizontalRight = false;
            // 水平攻击（向右）
            for (let x = piece.x + 1; x < BOARD_WIDTH; x++) {
                if (!gameBoard[piece.y][x]) {
                    // 空位 - 如果还没跳过则继续
                    if (jumpedHorizontalRight) {
                        // 已经跳过，不能攻击空位
                        break;
                    }
                } else {
                    if (!jumpedHorizontalRight) {
                        jumpedHorizontalRight = true; // 找到要跳过的棋子
                    } else {
                        // 这是跳过后的目标
                        attackZones.push({ x, y: piece.y });
                        break;
                    }
                }
            }
            
            let jumpedHorizontalLeft = false;
            // 水平攻击（向左）
            for (let x = piece.x - 1; x >= 0; x--) {
                if (!gameBoard[piece.y][x]) {
                    if (jumpedHorizontalLeft) {
                        break;
                    }
                } else {
                    if (!jumpedHorizontalLeft) {
                        jumpedHorizontalLeft = true;
                    } else {
                        attackZones.push({ x, y: piece.y });
                        break;
                    }
                }
            }

            let jumpedVerticalDown = false;
            // 垂直攻击（向下）
            for (let y = piece.y + 1; y < BOARD_HEIGHT; y++) {
                if (!gameBoard[y][piece.x]) {
                    if (jumpedVerticalDown) {
                        break;
                    }
                } else {
                    if (!jumpedVerticalDown) {
                        jumpedVerticalDown = true;
                    } else {
                        attackZones.push({ x: piece.x, y });
                        break;
                    }
                }
            }

            let jumpedVerticalUp = false;
            // 垂直攻击（向上）
            for (let y = piece.y - 1; y >= 0; y--) {
                if (!gameBoard[y][piece.x]) {
                    if (jumpedVerticalUp) {
                        break;
                    }
                } else {
                    if (!jumpedVerticalUp) {
                        jumpedVerticalUp = true;
                    } else {
                        attackZones.push({ x: piece.x, y });
                        break;
                    }
                }
            }
            break;

        default:
            // 对于其他所有棋子，攻击区域与有效移动相同
            return getValidMoves(piece);
    }

    return attackZones;
}

// 初始化游戏
function initGame() {
    // 重置游戏状态
    gameBoard = [];
    enemyPieces = [];
    score = 0;
    round = 1;
    gameOver = false;

    // 清空上一步移动的高亮
    lastMoveFrom = null;
    lastMoveTo = null;

    // 更新UI
    scoreElement.textContent = score;
    totalScoreElement.textContent = totalScore;
    highScoreElement.textContent = highScore;
    roundElement.textContent = round;

    // 创建空的游戏棋盘
    for (let y = 0; y < BOARD_HEIGHT; y++) {
        const row = [];
        for (let x = 0; x < BOARD_WIDTH; x++) {
            row.push(null);
        }
        gameBoard.push(row);
    }

    // 放置玩家的车
    const playerX = Math.floor(BOARD_WIDTH / 2);
    const playerY = BOARD_HEIGHT - 1;
    playerPiece = {
        type: PIECE_TYPES.ROOK,
        x: playerX,
        y: playerY,
        isPlayer: true
    };
    gameBoard[playerY][playerX] = playerPiece;

    // 放置敌方卒子
    const enemyPositions = [
        { x: 1, y: 1 },
        { x: 3, y: 1 },
        { x: 5, y: 1 }
    ];

    enemyPositions.forEach(pos => {
        const enemyPiece = {
            type: { ...PIECE_TYPES.PAWN, value: getUpgradedValue('PAWN') },
            x: pos.x,
            y: pos.y,
            isPlayer: false
        };
        gameBoard[pos.y][pos.x] = enemyPiece;
        enemyPieces.push(enemyPiece);
    });

    preloadSounds();
    // 渲染棋盘
    renderBoard(true);
}

// 渲染游戏棋盘
function renderBoard(fullRender = false) {
    if (fullRender || gameBoardElement.children.length === 0) {
        // 完整渲染 - 创建所有格子
        gameBoardElement.innerHTML = '';

        for (let y = 0; y < BOARD_HEIGHT; y++) {
            for (let x = 0; x < BOARD_WIDTH; x++) {
                const cell = document.createElement('div');
                cell.className = 'cell';
                cell.dataset.x = x;
                cell.dataset.y = y;
                cell.addEventListener('click', () => handleCellClick(x, y));
                gameBoardElement.appendChild(cell);
            }
        }
    }

    // 总是获取玩家棋子的有效移动
    const playerMoves = playerPiece ? getValidMoves(playerPiece) : [];

    // 如果启用辅助模式，获取敌方攻击区域
    let enemyAttackZones = [];
    if (assistMode) {
        enemyPieces.forEach(enemyPiece => {
            const attacks = getEnemyAttackZones(enemyPiece);
            enemyAttackZones = enemyAttackZones.concat(attacks);
        });

        // 同时标记危险的敌方棋子
        // （如果吃掉这些棋子会让玩家陷入危险）
        enemyPieces.forEach(enemyPiece => {
            // 检查玩家是否可以吃掉这个棋子
            if (playerMoves.some(move => move.x === enemyPiece.x && move.y === enemyPiece.y)) {
                // 检查吃掉这个棋子是否会让玩家陷入危险
                // 通过临时移除棋子来模拟吃子
                const originalPiece = gameBoard[enemyPiece.y][enemyPiece.x];
                gameBoard[enemyPiece.y][enemyPiece.x] = null;

                // 检查其他敌方棋子是否可以攻击玩家将要到达的位置
                const wouldBeInDanger = enemyPieces.some(otherEnemyPiece => {
                    if (otherEnemyPiece === enemyPiece) return false; // 跳过被吃掉的棋子
                    const otherAttacks = getEnemyAttackZones(otherEnemyPiece);
                    return otherAttacks.some(attack => attack.x === enemyPiece.x && attack.y === enemyPiece.y);
                });

                // 恢复棋子
                gameBoard[enemyPiece.y][enemyPiece.x] = originalPiece;

                // 如果吃子会很危险，将这个敌方棋子位置标记为危险
                if (wouldBeInDanger) {
                    enemyAttackZones.push({ x: enemyPiece.x, y: enemyPiece.y });
                }
            }
        });

    }
    
    // 用当前状态更新所有格子
    for (let y = 0; y < BOARD_HEIGHT; y++) {
        for (let x = 0; x < BOARD_WIDTH; x++) {
            const cellIndex = y * BOARD_WIDTH + x;
            const cell = gameBoardElement.children[cellIndex];
            const arrive = playerMoves.some(move => move.x === x && move.y === y)
            const danger = enemyAttackZones.some(zone => zone.x === x && zone.y === y)

            // 清除之前的类和内容
            cell.className = 'cell';
            cell.innerHTML = '';

            // 如果存在棋子则添加
            const piece = gameBoard[y][x];
            if (piece) {
                const pieceElement = document.createElement('div');
                pieceElement.className = `piece ${piece.isPlayer ? 'player' : 'enemy'} piece-${piece.type.type.toLowerCase()}`;
                pieceElement.textContent = piece.type.name;
                pieceElement.dataset.pieceId = `${piece.type.type}-${x}-${y}`;
                cell.appendChild(pieceElement);

                // 总是高亮玩家棋子
                if (piece.isPlayer) {
                    pieceElement.classList.add('selected');
                }
            }

            // 总是高亮玩家的有效移动
            if (arrive && !danger) {
                cell.classList.add('valid-move');
            }

            // 如果启用辅助模式，高亮敌方攻击区域
            if (assistMode && danger) {
                cell.classList.add('enemy-attack-zone');
            }

            // 高亮上一步移动
            if (lastMoveFrom && lastMoveFrom.x === x && lastMoveFrom.y === y) {
                cell.classList.add('last-move');
            }
            if (lastMoveTo && lastMoveTo.x === x && lastMoveTo.y === y) {
                cell.classList.add('last-move');
            }
        }
    }
}

// 处理格子点击
function handleCellClick(x, y) {
    if (gameOver) return;

    const clickedPiece = gameBoard[y][x];

    // 如果点击了玩家自己的棋子，什么都不做（因为我们自动选择）
    if (clickedPiece && clickedPiece.isPlayer) {
        return;
    }

    // 总是显示玩家棋子的有效移动
    const playerMoves = getValidMoves(playerPiece);

    // 如果点击位置是有效移动，移动到那里
    if (playerMoves.some(move => move.x === x && move.y === y)) {
        movePlayerPiece(x, y);
        return;
    }

    // 如果点击了无效位置，什么都不做（可以显示消息）
}

// 获取棋子的有效移动
function getValidMoves(piece) {
    const moves = [];

    switch (piece.type.type) {
        case 'ROOK':
            // 车水平和垂直移动
            // 水平移动（向右）
            for (let x = piece.x + 1; x < BOARD_WIDTH; x++) {
                moves.push({ x, y: piece.y });
                if (gameBoard[piece.y][x]) break; // 遇到障碍物停止
            }
            // 水平移动（向左）
            for (let x = piece.x - 1; x >= 0; x--) {
                moves.push({ x, y: piece.y });
                if (gameBoard[piece.y][x]) break; // 遇到障碍物停止
            }
            // 垂直移动（向下）
            for (let y = piece.y + 1; y < BOARD_HEIGHT; y++) {
                moves.push({ x: piece.x, y });
                if (gameBoard[y][piece.x]) break; // 遇到障碍物停止
            }
            // 垂直移动（向上）
            for (let y = piece.y - 1; y >= 0; y--) {
                moves.push({ x: piece.x, y });
                if (gameBoard[y][piece.x]) break; // 遇到障碍物停止
            }
            break;
            
        case 'CANNON':
            // 炮像车一样移动，但需要跳过一个棋子来吃子
            let jumpedHorizontalRight = false;
            // 水平移动（向右）
            for (let x = piece.x + 1; x < BOARD_WIDTH; x++) {
                if (!gameBoard[piece.y][x]) {
                    if (!jumpedHorizontalRight) {
                        moves.push({ x, y: piece.y });
                    }
                } else {
                    if (!jumpedHorizontalRight) {
                        jumpedHorizontalRight = true;
                    } else {
                        if (gameBoard[piece.y][x].isPlayer !== piece.isPlayer) {
                            moves.push({ x, y: piece.y });
                        }
                        break;
                    }
                }
            }
            
            let jumpedHorizontalLeft = false;
            // 水平移动（向左）
            for (let x = piece.x - 1; x >= 0; x--) {
                if (!gameBoard[piece.y][x]) {
                    if (!jumpedHorizontalLeft) {
                        moves.push({ x, y: piece.y });
                    }
                } else {
                    if (!jumpedHorizontalLeft) {
                        jumpedHorizontalLeft = true;
                    } else {
                        if (gameBoard[piece.y][x].isPlayer !== piece.isPlayer) {
                            moves.push({ x, y: piece.y });
                        }
                        break;
                    }
                }
            }

            let jumpedVerticalDown = false;
            // 垂直移动（向下）
            for (let y = piece.y + 1; y < BOARD_HEIGHT; y++) {
                if (!gameBoard[y][piece.x]) {
                    if (!jumpedVerticalDown) {
                        moves.push({ x: piece.x, y });
                    }
                } else {
                    if (!jumpedVerticalDown) {
                        jumpedVerticalDown = true;
                    } else {
                        if (gameBoard[y][piece.x].isPlayer !== piece.isPlayer) {
                            moves.push({ x: piece.x, y });
                        }
                        break;
                    }
                }
            }

            let jumpedVerticalUp = false;
            // 垂直移动（向上）
            for (let y = piece.y - 1; y >= 0; y--) {
                if (!gameBoard[y][piece.x]) {
                    if (!jumpedVerticalUp) {
                        moves.push({ x: piece.x, y });
                    }
                } else {
                    if (!jumpedVerticalUp) {
                        jumpedVerticalUp = true;
                    } else {
                        if (gameBoard[y][piece.x].isPlayer !== piece.isPlayer) {
                            moves.push({ x: piece.x, y });
                        }
                        break;
                    }
                }
            }
            break;
            
        case 'KNIGHT':
            // 马走日字形
            const knightMoves = [
                { x: piece.x + 1, y: piece.y - 2 },
                { x: piece.x + 2, y: piece.y - 1 },
                { x: piece.x + 2, y: piece.y + 1 },
                { x: piece.x + 1, y: piece.y + 2 },
                { x: piece.x - 1, y: piece.y + 2 },
                { x: piece.x - 2, y: piece.y + 1 },
                { x: piece.x - 2, y: piece.y - 1 },
                { x: piece.x - 1, y: piece.y - 2 }
            ];

            // 检查路径上的障碍物（中国象棋的马可能被蹩腿）
            for (const move of knightMoves) {
                if (move.x >= 0 && move.x < BOARD_WIDTH && move.y >= 0 && move.y < BOARD_HEIGHT) {
                    // 计算可能阻挡的棋子位置
                    let blockingX = piece.x;
                    let blockingY = piece.y;

                    // 确定检查阻挡的方向
                    if (Math.abs(move.x - piece.x) === 2) {
                        blockingX = piece.x + (move.x > piece.x ? 1 : -1);
                    } else {
                        blockingY = piece.y + (move.y > piece.y ? 1 : -1);
                    }

                    // 如果路径没有被阻挡
                    if (!gameBoard[blockingY][blockingX]) {
                        // 如果目标位置为空或有敌方棋子
                        if (!gameBoard[move.y][move.x] || gameBoard[move.y][move.x].isPlayer !== piece.isPlayer) {
                            moves.push(move);
                        }
                    }
                }
            }
            break;
            
        case 'ELEPHANT':
            // 象走田字形，斜向移动2步
            const elephantMoves = [
                { x: piece.x + 2, y: piece.y + 2 },
                { x: piece.x + 2, y: piece.y - 2 },
                { x: piece.x - 2, y: piece.y + 2 },
                { x: piece.x - 2, y: piece.y - 2 }
            ];

            for (const move of elephantMoves) {
                if (move.x >= 0 && move.x < BOARD_WIDTH && move.y >= 0 && move.y < BOARD_HEIGHT) {
                    // 检查对角线中心的阻挡棋子
                    const blockingX = piece.x + (move.x > piece.x ? 1 : -1);
                    const blockingY = piece.y + (move.y > piece.y ? 1 : -1);

                    if (!gameBoard[blockingY][blockingX]) {
                        // 如果目标位置为空或有敌方棋子
                        if (!gameBoard[move.y][move.x] || gameBoard[move.y][move.x].isPlayer !== piece.isPlayer) {
                            moves.push(move);
                        }
                    }
                }
            }
            break;

        case 'ADVISOR':
            // 士斜向移动1步
            const advisorMoves = [
                { x: piece.x + 1, y: piece.y + 1 },
                { x: piece.x + 1, y: piece.y - 1 },
                { x: piece.x - 1, y: piece.y + 1 },
                { x: piece.x - 1, y: piece.y - 1 }
            ];

            for (const move of advisorMoves) {
                if (move.x >= 0 && move.x < BOARD_WIDTH && move.y >= 0 && move.y < BOARD_HEIGHT) {
                    // 如果目标位置为空或有敌方棋子
                    if (!gameBoard[move.y][move.x] || gameBoard[move.y][move.x].isPlayer !== piece.isPlayer) {
                        moves.push(move);
                    }
                }
            }
            break;
            
        case 'GENERAL':
            // 将水平或垂直移动一步
            const generalMoves = [
                { x: piece.x + 1, y: piece.y },
                { x: piece.x - 1, y: piece.y },
                { x: piece.x, y: piece.y + 1 },
                { x: piece.x, y: piece.y - 1 }
            ];

            for (const move of generalMoves) {
                if (move.x >= 0 && move.x < BOARD_WIDTH && move.y >= 0 && move.y < BOARD_HEIGHT) {
                    // 如果目标位置为空或有敌方棋子
                    if (!gameBoard[move.y][move.x] || gameBoard[move.y][move.x].isPlayer !== piece.isPlayer) {
                        moves.push(move);
                    }
                }
            }
            break;

        case 'PAWN':
            // 卒的移动根据是谁的棋子而不同
            if (piece.isPlayer) {
                // 玩家的卒可以向前移动
                if (piece.y > 0) {
                    moves.push({ x: piece.x, y: piece.y - 1 });
                }
            } else {
                // 敌方卒可以向四个方向移动
                if (piece.y > 0) {
                    moves.push({ x: piece.x, y: piece.y - 1 }); // 向上
                }
                if (piece.y < BOARD_HEIGHT - 1) {
                    moves.push({ x: piece.x, y: piece.y + 1 }); // 向下
                }
                if (piece.x > 0) {
                    moves.push({ x: piece.x - 1, y: piece.y }); // 向左
                }
                if (piece.x < BOARD_WIDTH - 1) {
                    moves.push({ x: piece.x + 1, y: piece.y }); // 向右
                }
            }
            break;
    }

    // 过滤掉会吃掉玩家自己棋子的移动
    return moves.filter(move => {
        const targetPiece = gameBoard[move.y][move.x];
        return !targetPiece || targetPiece.isPlayer !== piece.isPlayer;
    });
}

// 移动玩家的棋子
function movePlayerPiece(x, y) {
    const fromX = playerPiece.x;
    const fromY = playerPiece.y;
    const targetPiece = gameBoard[y][x];

    // 更新上一步移动跟踪
    lastMoveFrom = { x: fromX, y: fromY };
    lastMoveTo = { x, y };

    // 如果目标位置有棋子，将其分值加到分数中
    if (targetPiece) {
        // 为吃子创建视觉效果
        const captureEffect = document.createElement('div');
        captureEffect.className = 'capture-effect';
        captureEffect.textContent = `+${targetPiece.type.value}`;
        document.body.appendChild(captureEffect);

        // 将效果定位在被吃棋子附近
        const cellRect = document.querySelector(`.cell[data-x="${x}"][data-y="${y}"]`).getBoundingClientRect();
        captureEffect.style.left = `${cellRect.left + cellRect.width/2}px`;
        captureEffect.style.top = `${cellRect.top}px`;

        // 动画并移除
        setTimeout(() => {
            captureEffect.style.opacity = '0';
            captureEffect.style.transform = 'translateY(-30px)';
            setTimeout(() => document.body.removeChild(captureEffect), 1000);
        }, 10);

        combo += 1;
        score += targetPiece.type.value;
        scoreElement.textContent = score;
        if (soundToggle.className === 'sound-on') {
            playSound();
        }

        // 从敌方棋子数组中移除被吃的棋子
        enemyPieces = enemyPieces.filter(p => p !== targetPiece);
    } else {
        combo = 0;
    }

    // 更新棋盘
    gameBoard[playerPiece.y][playerPiece.x] = null;
    gameBoard[y][x] = playerPiece;

    // 更新玩家棋子位置
    playerPiece.x = x;
    playerPiece.y = y;

    // 重新渲染棋盘以显示新的有效移动
    renderBoard();

    // 检查玩家移动后游戏是否结束
    if (!checkGameOver()) {
        // 敌方回合
        setTimeout(enemyTurn, 800);
    }
}

function preloadSounds() {
    new Audio('sounds/common.wav');
    new Audio('sounds/headshot.wav');
    new Audio('sounds/2.wav');
    new Audio('sounds/3.wav');
    new Audio('sounds/4.wav');
    new Audio('sounds/5.wav');
    new Audio('sounds/6.wav');
    new Audio('sounds/7.wav');
    new Audio('sounds/8.wav');
}

function playSound() {
    new Audio('sounds/common.wav').play();
    if (combo === 1) {
        new Audio('sounds/headshot.wav').play();
    } else if (combo === 2) {
        new Audio('sounds/2.wav').play();
    } else if (combo === 3) {
        new Audio('sounds/3.wav').play();
    } else if (combo === 4) {
        new Audio('sounds/4.wav').play();
    } else if (combo === 5) {
        new Audio('sounds/5.wav').play();
    } else if (combo === 6) {
        new Audio('sounds/6.wav').play();
    } else if (combo === 7) {
        new Audio('sounds/7.wav').play();
    } else if (combo >= 8) {
        new Audio('sounds/8.wav').play();
    } else {

    }
}

// 敌方回合
function enemyTurn() {
    // 检查是否有敌方棋子可以吃掉玩家
    for (const enemyPiece of enemyPieces) {
        const enemyMoves = getValidMoves(enemyPiece);

        // 检查是否有移动可以吃掉玩家
        const captureMove = enemyMoves.find(move =>
            move.x === playerPiece.x && move.y === playerPiece.y
        );

        if (captureMove) {
            // 吃掉玩家
            gameBoard[enemyPiece.y][enemyPiece.x] = null;
            gameBoard[playerPiece.y][playerPiece.x] = enemyPiece;
            enemyPiece.x = playerPiece.x;
            enemyPiece.y = playerPiece.y;

            // 游戏结束 - 传递击败的棋子
            endGame("敌方棋子吃掉了你的棋子！", enemyPiece);
            return;
        }
    }

    // 检查是否有敌方棋子被玩家威胁
    const threatenedPieces = enemyPieces.filter(enemyPiece => {
        const playerMoves = getValidMoves(playerPiece);
        return playerMoves.some(move =>
            move.x === enemyPiece.x && move.y === enemyPiece.y
        );
    });

    if (threatenedPieces.length > 0) {
        // 移动一个随机的被威胁棋子
        const pieceToMove = threatenedPieces[Math.floor(Math.random() * threatenedPieces.length)];
        const validMoves = getValidMoves(pieceToMove);

        if (validMoves.length > 0) {
            const randomMove = validMoves[Math.floor(Math.random() * validMoves.length)];

            // 移动棋子
            gameBoard[pieceToMove.y][pieceToMove.x] = null;

            // 如果目标位置有棋子（由于getValidMoves过滤，不应该是玩家的棋子）
            if (gameBoard[randomMove.y][randomMove.x]) {
                // 从敌方棋子数组中移除被吃的棋子
                enemyPieces = enemyPieces.filter(p =>
                    p !== gameBoard[randomMove.y][randomMove.x]
                );
            }

            gameBoard[randomMove.y][randomMove.x] = pieceToMove;
            pieceToMove.x = randomMove.x;
            pieceToMove.y = randomMove.y;

            // 结束敌方回合
            endEnemyTurn();
            return;
        }
    }
    
    // 如果没有被威胁的棋子或被威胁棋子没有有效移动，
    // 移动一个随机棋子
    if (enemyPieces.length > 0) {
        const randomIndex = Math.floor(Math.random() * enemyPieces.length);
        const pieceToMove = enemyPieces[randomIndex];
        const validMoves = getValidMoves(pieceToMove);

        if (validMoves.length > 0) {
            const randomMove = validMoves[Math.floor(Math.random() * validMoves.length)];

            // 移动棋子
            gameBoard[pieceToMove.y][pieceToMove.x] = null;

            // 如果目标位置有棋子（由于getValidMoves过滤，不应该是玩家的棋子）
            if (gameBoard[randomMove.y][randomMove.x]) {
                // 从敌方棋子数组中移除被吃的棋子
                enemyPieces = enemyPieces.filter(p =>
                    p !== gameBoard[randomMove.y][randomMove.x]
                );
            }

            gameBoard[randomMove.y][randomMove.x] = pieceToMove;
            pieceToMove.x = randomMove.x;
            pieceToMove.y = randomMove.y;
        }
    }

    // 结束敌方回合
    endEnemyTurn();
}

// 结束敌方回合并开始新一轮
function endEnemyTurn() {
    round++;
    roundElement.textContent = round;

    // 每4回合添加3个新棋子
    if (round % 4 === 0) {
        addNewPieces(3);
    }

    // 渲染更新的棋盘（为敌方移动和新棋子进行完整渲染）
    renderBoard();

    // 检查敌方移动后游戏是否结束
    checkGameOver();
}

// 向棋盘添加新的敌方棋子
function addNewPieces(count) {
    const pieceTypes = Object.values(PIECE_TYPES);
    const emptyPositions = [];

    // 找到所有空位置
    for (let y = 0; y < BOARD_HEIGHT - 2; y++) { // 避开底部两行
        for (let x = 0; x < BOARD_WIDTH; x++) {
            if (!gameBoard[y][x]) {
                emptyPositions.push({ x, y });
            }
        }
    }

    // 打乱空位置
    for (let i = emptyPositions.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [emptyPositions[i], emptyPositions[j]] = [emptyPositions[j], emptyPositions[i]];
    }

    // 添加新棋子
    const addedPieces = [];
    for (let i = 0; i < Math.min(count, emptyPositions.length); i++) {
        const pos = emptyPositions[i];
        const randomType = pieceTypes[Math.floor(Math.random() * pieceTypes.length)];

        // 创建具有升级分值的棋子
        const upgradedType = { ...randomType };
        upgradedType.value = getUpgradedValue(randomType.type);

        const newPiece = {
            type: upgradedType,
            x: pos.x,
            y: pos.y,
            isPlayer: false
        };

        gameBoard[pos.y][pos.x] = newPiece;
        enemyPieces.push(newPiece);
        addedPieces.push(newPiece);
    }

    // 显示关于新棋子的通知
    if (addedPieces.length > 0) {
        showNotification(`${addedPieces.length} 个新的敌方棋子出现了！`);
    }
}

// 显示通知消息
function showNotification(message) {
    // 如果通知元素不存在则创建
    let notification = document.getElementById('game-notification');
    if (!notification) {
        notification = document.createElement('div');
        notification.id = 'game-notification';
        notification.className = 'game-notification hidden';
        document.body.appendChild(notification);
    }

    // 设置消息并显示
    notification.textContent = message;
    notification.classList.remove('hidden');

    // 延迟后隐藏
    setTimeout(() => {
        notification.classList.add('hidden');
    }, 3000);
}

// 检查游戏是否结束
function checkGameOver() {
    // 检查玩家是否没有有效移动
    const playerMoves = getValidMoves(playerPiece);
    if (playerMoves.length === 0) {
        endGame("你没有有效的移动了！");
        return true;
    }

    return false;
}

// 结束游戏
function endGame(reason, defeatingPiece = null) {
    gameOver = true;

    // 将当前分数加到总分数中
    totalScore += score;
    localStorage.setItem('chessTotalScore', totalScore);
    totalScoreElement.textContent = totalScore;

    // 如果需要，更新最高分
    if (score > highScore) {
        highScore = score;
        localStorage.setItem('chessGameHighScore', highScore);
        highScoreElement.textContent = highScore;
    }

    // 显示游戏结束屏幕
    finalScoreElement.textContent = `你的分数: ${score}`;

    // 如果有击败棋子则显示
    const defeatInfoElement = document.getElementById('defeat-info');
    const defeatingPieceElement = document.getElementById('defeating-piece');

    if (defeatingPiece) {
        defeatingPieceElement.innerHTML = '';
        const pieceElement = document.createElement('div');
        pieceElement.className = `piece enemy defeated piece-${defeatingPiece.type.type.toLowerCase()}`;
        pieceElement.textContent = defeatingPiece.type.name;
        defeatingPieceElement.appendChild(pieceElement);
        defeatInfoElement.style.display = 'block';
    } else {
        defeatInfoElement.style.display = 'none';
    }
    
    // 根据分数设置消息
    let message = "";
    if (score >= 3000) {
        message = "弓马骑射洒热血，突破重围显英豪!";
    } else if (score >= 2000) {
        message = "一人一枪一匹马，疆场尽驰骋!";
    } else if (score >= 1000) {
        message = "匹马单枪出重围，英风锐气敌胆寒";
    } else if (score >= 500) {
        message = "翩若惊鸿，婉若游龙";
    } else {
        message = "魂归在何处，仰天长问三两声";
    }

    messageElement.textContent = message;
    gameOverElement.classList.remove('hidden');
}

// 商店功能
function openShop() {
    console.log('正在打开商店...');
    renderShop();
    if (shopElement) {
        shopElement.classList.remove('hidden');
        shopElement.style.display = 'flex';
        console.log('商店打开成功');
    } else {
        console.error('未找到商店元素');
    }
}

function closeShop() {
    console.log('正在关闭商店...');
    if (shopElement) {
        shopElement.classList.add('hidden');
        shopElement.style.display = 'none';
        console.log('商店关闭成功');
    }
}

function renderShop() {
    console.log('调用renderShop');
    const shopContent = document.getElementById('shop-content');
    if (!shopContent) {
        console.error('未找到shop-content元素');
        return;
    }
    console.log('清空商店内容');
    shopContent.innerHTML = '';

    // 商店头部
    const header = document.createElement('div');
    header.className = 'shop-header';
    header.innerHTML = `
        <h2>升级商店</h2>
        <p>总分数: ${totalScore}</p>
        <button id="close-shop" class="close-button">&times;</button>
    `;
    shopContent.appendChild(header);

    // 商店物品
    const itemsContainer = document.createElement('div');
    itemsContainer.className = 'shop-items';

    Object.keys(PIECE_TYPES).forEach(pieceType => {
        const currentValue = getUpgradedValue(pieceType);
        const upgradeCost = getUpgradeCost(pieceType);
        const upgradeLevel = pieceUpgrades[pieceType];

        const item = document.createElement('div');
        item.className = 'shop-item';
        item.innerHTML = `
            <div class="piece-info">
                <div class="legend-piece ${pieceType.toLowerCase()}">${PIECE_TYPES[pieceType].name}</div>
                <div class="piece-details">
                    <div>当前分数: ${currentValue}</div>
                    <div>升级等级: ${upgradeLevel}</div>
                    <div>升级费用: ${upgradeCost}</div>
                </div>
            </div>
            <button class="upgrade-btn" data-piece="${pieceType}" ${totalScore < upgradeCost ? 'disabled' : ''}>
                升级 (+50%)
            </button>
        `;
        itemsContainer.appendChild(item);
    });

    shopContent.appendChild(itemsContainer);

    // 添加事件监听器
    document.getElementById('close-shop').addEventListener('click', closeShop);

    document.querySelectorAll('.upgrade-btn').forEach(btn => {
        btn.addEventListener('click', (e) => {
            const pieceType = e.target.dataset.piece;
            upgradePiece(pieceType);
        });
    });
}

function upgradePiece(pieceType) {
    const cost = getUpgradeCost(pieceType);

    if (totalScore >= cost) {
        totalScore -= cost;
        pieceUpgrades[pieceType]++;

        // 立即更新棋盘上现有的棋子
        updateExistingPieces(pieceType);

        // 保存到localStorage
        localStorage.setItem('chessTotalScore', totalScore);
        localStorage.setItem('chessUpgrades', JSON.stringify(pieceUpgrades));

        // 更新UI
        totalScoreElement.textContent = totalScore;
        renderShop();

        const newValue = getUpgradedValue(pieceType);
        showNotification(`${PIECE_TYPES[pieceType].name} 升级成功! 新分数: ${newValue}`);
    }
}

// 事件监听器
startButton.addEventListener('click', () => {
    initGame();
    gameOverElement.classList.add('hidden');
    closeShop(); // 确保商店关闭
});

restartButton.addEventListener('click', () => {
    initGame();
    gameOverElement.classList.add('hidden');
    closeShop(); // 确保商店关闭
});

shopButton.addEventListener('click', () => {
    console.log('商店按钮被点击');
    openShop();
});

assistButton.addEventListener('click', () => {
    toggleAssistMode();
});

// 同时为商店背景添加点击事件以关闭它
shopElement.addEventListener('click', (e) => {
    if (e.target === shopElement) {
        closeShop();
    }
});

soundToggle.addEventListener("click", () => {
    if (soundToggle.className === 'sound-on') {
        soundToggle.className = 'sound-off';
        soundToggle.innerText = '🔇';
    } else {
        soundToggle.className = 'sound-on';
        soundToggle.innerText = '🔊';
    }
})

// 关闭游戏结束弹窗而不重新开始
const closeGameOverButton = document.getElementById('close-game-over');
if (closeGameOverButton) {
    closeGameOverButton.addEventListener('click', () => {
        gameOverElement.classList.add('hidden');
    });
}

// 页面加载时初始化游戏
window.addEventListener('DOMContentLoaded', () => {
    totalScoreElement.textContent = totalScore;

    // 确保商店在页面加载时是隐藏的
    if (shopElement) {
        shopElement.classList.add('hidden');
        shopElement.style.display = 'none';
    }

    initGame();
});
